package com.per.mybootall.test;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: yyy
 * Date: 2021/12/24
 * Time: 10:27
 * Description:这个没什么用，不用管
 */
public class test06 {
    public static void main(String[] args) {
        Map<String, Integer> test = new HashMap<>(20000);
        Random r = new Random(new Date().getTime());
        for (int i = 0;i<10000;i++){
            StringBuilder key = new StringBuilder();
            int value = 0;
            for (int j = 0;j<=r.nextInt(10);j++){
                key.append((char)(65+r.nextInt(26)));
                value = value*10 + r.nextInt(10) + 1;
            }
            test.put(key.toString(),value);
        }

        long time1 = System.currentTimeMillis();
        System.out.println("1--------------------:"+sortMap1(test));
        long time2 = System.currentTimeMillis();
        System.out.println("2--------------------:"+(time2-time1));
        System.out.println(sortMap2(test));
        time1 = System.currentTimeMillis();
        System.out.println("3--------------------:"+(time1-time2));
        System.out.println(sortMap3(test));
        time2 = System.currentTimeMillis();
        System.out.println(time2-time1);
        System.out.println(sortMap4(test));
        time1 = System.currentTimeMillis();
        System.out.println(time1-time2);
    }

    /**
     请给一个无序的 HashMap 排序（按 key 的字典序），并返回排序后 Map。
     **/
    public static Map<String, Integer> sortMap1(Map<String, Integer> map) {
        return map.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(oldVal, newVal) -> newVal, LinkedHashMap::new));
    }

    public static Map<String, Integer> sortMap2(Map<String, Integer> map) {
        return map.keySet().stream()
                .sorted()
                .collect(Collectors.toMap(each->each, map::get,(oldVal,newVal)->newVal,LinkedHashMap::new));
    }

    public static Map<String, Integer> sortMap3(Map<String, Integer> map) {
        return map.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.groupingBy(Map.Entry::getKey, LinkedHashMap::new, Collectors.mapping(Map.Entry::getValue, Collectors.summingInt(each -> each))));
        //简单写就是 .collect(Collectors.groupingBy(Map.Entry::getKey, LinkedHashMap::new, Collectors.summingInt(each -> each)));
    }

    public static Map<String, Integer> sortMap4(Map<String, Integer> map) {
        return map.entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(oldVal, newVal) -> newVal, TreeMap::new));
    }
}
